const { app, BrowserWindow, Menu, ipcMain, dialog, shell } = require('electron')
const path = require('node:path')
const waterMark = require('./waterMark')
const copyPdf = require('./copyPdf')
const process = require('node:process')
const os = require('node:os')
const Register = require('winreg'), regKey = new Register({
  hive: Register.HKLM,
  key: `\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts`
})

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      contextIsolation: false,
      nodeIntegration: true,
      nodeIntegrationInWorker: true,
      preload: path.join(__dirname, 'preload.js')
    },
    maximizable: false,
    resizable: false,
    parent: String(+new Date()),
    icon: path.join(__dirname, './images/pdf.ico')
  })

  //  win.webContents.openDevTools()

  win.loadFile('index.html')
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
  //__dirname
  const userdir = os.homedir()
  const appUrl = app.getPath("exe")
  const lnkUrl = path.join(userdir, 'Desktop', 'PDF工具箱.lnk')

  //创建快捷方式
  try {
    fs.accessSync(lnkUrl)
    const res = shell.writeShortcutLink( lnkUrl, 'replace', { target: appUrl })
  } catch (error) {
    const res = shell.writeShortcutLink( lnkUrl, 'create', { target: appUrl })
  }
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

ipcMain.on('open-file-dialog', function (event) {
  dialog.showOpenDialog({
    title: '选择加水印的PDF文件！',
    defaultPath: '1.pdf',
    filters: [{ name: 'pdf', extensions: ['pdf'] }],
    buttonLable: '选择',
    properties: ['openFile',]
  }).then((res) => {
    if (!res.canceled) {
      event.sender.send('selected-files', res)
    }
  }).catch((err) => {
    console.log(err)
  })
})

ipcMain.on('save-file-dialog', function (event) {
  dialog.showSaveDialog({
    title: '选择要保存的文件名',
    buttonLabel: '保存',
    filters: [{ name: 'pdf', extensions: ['pdf'] }],
  }).then((res) => {
    if (!res.canceled) {
      event.sender.send('saved-files', res)
    }
  }).catch((err) => {
    console.log(err)
  })
})

ipcMain.on('add-watermark', async function (event, args) {
  const j = args[0]

  if (typeof j.color == 'string') {
    let str = j.color.replace('rgba(', '')
    str = str.replace(')', '')
    let ar = str.split(',');
    if (ar.length === 4) {
      j.color_ar = ar
    }

    const s = await waterMark.add_mark(j)
    event.sender.send('add-watermark-end', [s])
  }
})

ipcMain.on('save-sfile-dialog', function (event) {
  dialog.showSaveDialog({
    title: '选择合并后保存的文件名',
    buttonLabel: '保存',
    filters: [{ name: 'pdf', extensions: ['pdf'] }],
  }).then((res) => {
    if (!res.canceled) {
      event.sender.send('saved-sfiles', res)
    }
  }).catch((err) => {
    console.log(err)
  })
})

ipcMain.on('save-file-dialog', function (event) {
  dialog.showSaveDialog({
    title: '选择添加水印后保存的文件名',
    buttonLabel: '保存',
    filters: [{ name: 'pdf', extensions: ['pdf'] }],
  }).then((res) => {
    if (!res.canceled) {
      event.sender.send('saved-files', res)
    }
  }).catch((err) => {
    console.log(err)
  })
})

ipcMain.on('get-fonts', function (event) {

  regKey.values(function (err, items) {
    if (err) {
      event.sender.send('get-fonts-end', [])
    } else {
      const res = []
      items.map((item, idx) => {
        if (item.value.indexOf('.ttf') > 1) {
          res.push({
            name: item.name.replace('(TrueType)', ''),
            font: item.value
          })
        }
      })
      res.sort((a, b) => {
        return a.name - b.name;
      })
      event.sender.send('get-fonts-end', res)
    }
  })

})

ipcMain.on('open-mfile-dialog', function (event) {
  dialog.showOpenDialog({
    title: '选择要合并的PDF文件，可以多选！',
    defaultPath: '1.pdf',
    filters: [{ name: 'pdf', extensions: ['pdf'] }],
    buttonLable: '选择',
    properties: ['openFile', 'multiSelections']
  }).then((res) => {
    if (!res.canceled) {
      event.sender.send('selected-mfiles', res)
    }
  }).catch((err) => {
    console.log(err)
  })
})

ipcMain.on('merge-files', async function (event, args) {
  const j = args[0]
  // file: $("#merge_list").val(), //待处理
  // repeat: $("#remove_repeat").val(),
  // sfont: $("#merge_sfile").val(),
  console.log(args)
  if (j.files.length > 1) {

    const s = await copyPdf.mergePages(j)
    event.sender.send('merge-files-end', [s])
  }
})

ipcMain.on('open-split-file-dialog', async function (event) {
  const res = await dialog.showOpenDialogSync({
    title: '选择要分割的PDF文件！',
    defaultPath: '1.pdf',
    filters: [{ name: 'pdf', extensions: ['pdf'] }],
    buttonLable: '选择',
    properties: ['openFile']
  })
  if (res) {
    const n = await copyPdf.getPageCount(res[0])
    event.sender.send('selected-split-file', { file: res[0], count: n })
  }
})

ipcMain.on('save-split-dir-dialog', function (event, args) {
  dialog.showOpenDialog({
    title: '选择分割后文件保存的路径！',
    defaultPath: args ? args[0] : '',
    //  filters: [{ name: 'pdf', extensions: ['pdf'] }],
    buttonLable: '选择',
    properties: ['openDirectory']
  }).then((res) => {
    if (!res.canceled) {
      event.sender.send('saved-split-dir', res)
    }
  }).catch((err) => {
    console.log(err)
  })
})

ipcMain.on('split-files', async function (event, args) {
  const j = args[0]
  // range: $("#split_list").val(), //待处理
  // file: $("#split_file").val(),
  // sdir: $("#split_files").val(),
  console.log(args)
  if (j.range.length > 0) {

    const s = await copyPdf.splitPages(j)
    event.sender.send('split-files-end', s)
  }
})

const openDefaultBrowser = function(url) {
  const exec = require('child_process').exec
  switch ( process.platform ) {
    case 'darwin':
      exec('open ' + url);
      break;
    case 'win32':
      exec('start ' + url);
      break;
    default:
      exec('xdg-open', [url])
  }
}

ipcMain.on('open-url', async function(event, args) {
  openDefaultBrowser(args)
//  event.sender.send('open-url-end')
})

//移除自带菜单
Menu.setApplicationMenu(null)